//
//  ComfirmOrderNoSeatViewController.m
//  OrderSeat
//
//  Created by 王威 on 13-12-22.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "ComfirmOrderNoSeatViewController.h"
#import "ShopHomeViewController.h"
#import "MyOrderViewController.h"
#import "OrderDetailViewController.h"
#import "SeatViewController.h"

#define DATE_PICKER_HEIGHT 160
#define DONE_TOOLBAR_HEIGHT 30

@implementation ComfirmOrderNoSeatViewController

- (id)initWithShopId:(NSString*)shopId
{
    self = [super initWithNibClass:[ComfirmOrderNoSeatViewController class]];
    if (self) {
        self.shopId = shopId;
        _dataSource = [[ComfirmOrderNoSeatDataSource alloc] initWithVC:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    [self totalAction];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"确认订单"];
    
    _otherView.hidden = YES;
    _myPhoneLabel.text = [AppSetting tel];

    self.dateTF.text = [self getTodayString];
    self.dateTF.inputView = self.datePicker;
    self.dateTF.inputAccessoryView = _doneBar;
    
    [_doneBtn addTarget:self action:@selector(selectedDateAction:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addTarget:self action:@selector(tapGestureAction:)];
    [self reLayoutSubviews];
}

- (void)leftButtonClick:(id)sender
{
    if (_orderSuccess) {
        [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
        [self pushOrPopViewController:[ShopHomeViewController class]];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma 点击手势回调函数
- (void)tapGestureAction:(UITapGestureRecognizer*)tapRecognizer
{
    [_otherPhoneTF resignFirstResponder];
    [_otherNameTF resignFirstResponder];
    [_numberTF resignFirstResponder];
    [_dateTF resignFirstResponder];
    [_otherNameTF resignFirstResponder];
}

#pragma 开始编辑的时候防止键盘挡住文本框
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.theScrollview setContentOffset:CGPointMake(0, 100) animated:YES];
}

#pragma 退出编辑的时候恢复键盘位置
- (IBAction)TextField_DidEndOnExit:(id)sender
{
    [sender resignFirstResponder];
    [self.theScrollview setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)totalAction
{
    _totalCount = 0;
    _totalMoney = 0;
    
    for (NSDictionary *dic in _selectedDishList) {
        int count = [[dic objectForKey:@"fenshu"] intValue];
        float money = [[dic objectForKey:@"price"] floatValue];
        
        _totalCount += count;
        _totalMoney += money*count;
    }
    
    if (_packageEntity) {
        _totalCount = [[_packageEntity objectForKey:@"fenshu"] intValue];
        _totalMoney = [[_packageEntity objectForKey:@"price"] floatValue];
        _totalMoney = _totalMoney * _totalCount;
    }
    
    NSString *unit = _packageEntity ? @"份套餐" : @"道菜";
    self.totalCountLabel.text = [NSString stringWithFormat:@"/%d%@",_totalCount,unit];
    self.totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f元",_totalMoney];
}

- (void)selectedDateAction:(id)sender
{
    NSString *sdate = [_datePicker.date toStringWithFormat:@"yyyy-MM-dd"];
    NSString *ndate = [[NSDate date] toStringWithFormat:@"yyyy-MM-dd"];
    
    if ([sdate compare:ndate] == NSOrderedAscending) {
        [AppDelegate showMessage:@"就餐日期不能小于当前日期！"];
        return;
    }
    
    NSString *date = [_datePicker.date toString];
    NSString *today = [[NSDate date] toString];
    
    if ([date isEqualToString:today]) {
        date = [date stringByAppendingString:@" / 今天"];
    }
    
    [self.dateTF endEditing:YES];
    self.dateTF.text = date;
}

- (NSString *)getTodayString
{
    NSString *today = [[NSDate date] toString];
    today = [today stringByAppendingString:@" / 今天"];
    return today;
}

- (IBAction)selLunchOrDinnerAction:(id)sender
{
    self.btnLunch.selected = NO;
    self.btnDinner.selected = NO;
    [sender setSelected:YES];
}

- (IBAction)selectPhoneAction:(id)sender
{
    self.myPhoneButton.selected = [sender tag] == 1;
    self.otherPhoneButton.selected = [sender tag] == 2;
    
    _otherView.hidden = !_otherPhoneButton.selected;
    
    [self reLayoutSubviews];
}

#pragma 选择性别
- (IBAction)selGenderAction:(id)sender
{
    _sirBtn.selected = _ladyBtn.selected = NO;
    [sender setSelected:YES];
}

- (IBAction)submitOrderAction:(id)sender
{
    if (![self checkForm]) return;
    
    NSString *username = [AppSetting userName];
    NSString *shopId = _shopId;
    NSString *caipin = [self getDishString];
    NSString *seat = S_EMPTY;
    NSString *dinnerCount = _numberTF.text;
    NSString *orderTime = [_datePicker.date toStringWithFormat:@"yyyy-MM-dd"];
    NSString *zaowan = _btnLunch.selected ? @"1" : @"2";
    NSString *mobile = _myPhoneButton.selected ? [AppSetting tel] : _otherPhoneTF.text;
    NSString *url = S_EMPTY;
    
    if (_packageEntity) {
        NSString *packageId = [_packageEntity objectForKey:@"id"];
        NSString *packCount = [_packageEntity objectForKey:@"fenshu"];
        url = [NSString stringWithFormat:API_PACKAGE_ORDER,username,shopId,packageId,packCount,orderTime,zaowan,mobile,seat,S_EMPTY,S_EMPTY];
    }
    else {
        url = [NSString stringWithFormat:API_DISH_ORDER,username,shopId,caipin,dinnerCount,orderTime,zaowan,mobile,seat,S_EMPTY,S_EMPTY];
    }
    
    [_dataSource submitOrderWithURL:url];
}

- (NSString*)getDishString
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:5];
    for (NSDictionary *dic in _selectedDishList) {
        if ([[dic objectForKey:@"fenshu"] intValue] > 0) {
            NSString *cid = [dic objectForKey:@"id"];
            NSString *price = [dic objectForKey:@"price"];
            NSString *ccount = [dic objectForKey:@"fenshu"];
            
            NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:cid,@"cid",price,@"price",ccount,@"ccount", nil];
            [array addObject:dictionary];
        }
    }
    
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:array,@"caipin", nil];
    return [dictionary JSONString];
}

- (BOOL)checkForm
{
    if ([_numberTF.text isEqualToString:@""]) {
        [AppDelegate showMessage:@"请填写用餐人数"];
        return NO;
    }
    if (!_btnLunch.selected && !_btnDinner.selected) {
        [AppDelegate showMessage:@"请选择用餐时间(中餐或晚餐)"];
        return NO;
    }
    if (!_myPhoneButton.selected && !_otherPhoneButton.selected) {
        [AppDelegate showMessage:@"请选择订餐人的电话号码"];
        return NO;
    }
    if (_otherPhoneButton.selected) {
        if ([_otherPhoneTF.text isEqualToString:@""]) {
            [AppDelegate showMessage:@"请填写其他预订人的电话号码！"];
            return NO;
        }
        if ([_otherNameTF.text isEqualToString:@""]) {
            [AppDelegate showMessage:@"请填写其他预订人的姓氏！"];
            return NO;
        }
        if (!_sirBtn.selected && !_ladyBtn.selected) {
            [AppDelegate showMessage:@"请选择其他预订人的性别！"];
            return NO;
        }
    }
    
    return YES;
}

- (void)reLayoutSubviews
{    
    [UIView drawBorders:@[_headView,_phoneView,_totalView,_otherPhoneTF,_otherNameTF]];
    [UIView autoHeights:@[_headView, _phoneView]];
    [UIView autoLayoutVertical:@[_headView, _phoneView, _totalView, _btnSubmit]];
    
    [_theScrollview autoHeight];
}

#pragma 预定成功后，显示对话框
- (void)orderDidSuccess:(NSDictionary *)data
{
    self.orderSuccess = YES;
    self.orderId = [data objectForKey:@"order_id"];
    
    AlertWindowView *alert = [[AlertWindowView alloc] initWithMessage:@"恭喜您已预定成功" delegate:self buttonTitles:@[@"查看订单",@"去订座位"]];
    [self.view addSubview:alert];
    
    [alert showWindow];
}

- (void)alertWindow:(AlertWindowView *)alertWindow clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        OrderDetailViewController *orderVC = [[OrderDetailViewController alloc] initWithOrderId:_orderId andType:NewOrder];
        [self pushViewController:orderVC];
    }
    
    if (buttonIndex == 1) {
        ShopHomeViewController *vc = (ShopHomeViewController *)[self findControllerWithClass:[ShopHomeViewController class]];

        SeatViewController *seatVC = [[SeatViewController alloc] initWithShopId:_shopId];
        seatVC.data = vc.data;
        [self pushViewController:seatVC];
    }
}

@end

//=======================================================================================
#pragma ===================数据源、数据请求等封装============================================
//=======================================================================================

@implementation ComfirmOrderNoSeatDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
    }
    return self;
}

- (void)submitOrderWithURL:(NSString*)url
{
    [SVProgressHUD show];
    [self get:url];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    
    CLog(@"%@", request.responseString);
    
    NSDictionary *json = [request.responseData JSONValue];
    if ([[json objectForKey:@"error_code"] intValue] != 0) {
        return;
    }
    
    int state = [[json objectForKey:@"state"] intValue];
    if (state == 1) {
        [_viewController orderDidSuccess:json];
    }
    
    if (state == 2) {
        [AppDelegate showMessage:@"订单预定失败!"];
    }
}

@end
